import React, { useMemo, useState, useCallback } from 'react';
import { Select, Icon } from '@library';
import { Form, Input, Checkbox, Slider, Dropdown } from 'antd';
import uuid from 'uuid-v4';
import { SketchPicker } from 'react-color';
import { modeData } from '../datePicker/DatePickerController';
import ItemController from './_ItemController';
import ActionSettingController from './_ActionSetting';
import OptionSetting from '../components/optionSetting/OptionSetting';
import ButtonGroup from './buttonGroup/ButtonGroup';
import ActionButtonGroup from './actionButtonGroup/ActionButtonGroup';
import useControlOptions from '../../hooks/useControlOptions';
import { options } from './_ActionSetting';
import { TabsOptionProps, DataListProps } from './interface';
import Columns from './columns/Columns';
import CodeMirror from './../codeMirror/CodeMirror';

export interface DataItemProps {
  label: string;
  labelEn: string;
  value: string;
  key?: string;
  formName?: string;
  breadCrumbName?: string;
  dateFormat?: string;
  width?: number;
  fixed?: string | boolean;
  moneyFormat?: boolean;
  statusTransfer?: string;
  statusTransferEn?: string;
  text?: string;
  fontSize?: number;
  fontWeight?: number;
  color?: string;
  backgroundColor?: string;
  customizeStyleFlag?: boolean;
  clickScript?: string;
  serverSortFlag?: boolean
}

export const formItems = [
  { name: 'formName', label: '跳转表单', options, type: 'modalTableInModel' },
  { name: 'text', label: 'text', ghost: '!{{formName}}', },
  {
    name: 'width',
    label: '宽度',
    type: 'number',
    options: {
      min: 60,
      integer: true
    }
  },
  { name: 'statusTransfer', label: '值映射', type: 'textArea' },
  { name: 'statusTransferEn', label: '值映射(英文)', type: 'textArea' },
  { name: 'moneyFormat', label: '显示为金额', type: 'switch' },
  {
    name: 'dateFormat', label: '时间转换格式', type: 'select', options: {
      dataSource: modeData
    }
  },
  {
    name: 'fixed', label: '固定位置', type: 'radio', options: {
      dataSource: [
        { value: false, label: '无' },
        { value: 'left', label: '左侧' },
        { value: 'right', label: '右侧' },
      ]
    }
  }
];
const FormItem = Form.Item;
const getTabsOptionCombineColumns = (tabsOption: TabsOptionProps[]) => {

  let _temp = tabsOption?.reduce((all: any[], now) => {
    let _fileds = all.map(item => item.value);
    return all.concat(now.columns.filter(item => !_fileds.includes(item.value)));
  }, []);

  return _temp.map(item => ({
    label: item.title,
    labelEn: item.titleEn,
    value: item.dataIndex,
    key: item.key,
    id: item.key,
  }));
};

const DataListController = () => {
  const { options, changeControlProps, changeDataListCurrent } = useControlOptions<DataListProps>();
  const [index, setIndex] = useState<null | number>(null);
  const [curColumn, _setCurColumn] = useState<TabsOptionProps>({} as any);

  const setCurColumn = useCallback(
    (curColumn: TabsOptionProps, index?: number) => {
      setIndex(index!);
      _setCurColumn(curColumn);
      changeDataListCurrent(curColumn, setCurColumn);
    },
    [changeDataListCurrent]
  );

  const _options = useMemo(() => {
    return {
      dataSource: options.columns?.map(item => {
        return {
          label: item.title,
          labelEn: item.titleEn,
          value: item.dataIndex,
          key: item.key,
          id: item.key,
          formName: item.formName,
          breadCrumbName: item.breadCrumbName,
          dateFormat: item.dateFormat,
          width: item.width,
          fixed: item.fixed,
          moneyFormat: item.moneyFormat,
          statusTransfer: item.statusTransfer,
          statusTransferEn: item.statusTransferEn,
          text: item.text,
          fontSize: item.fontSize,
          fontWeight: item.fontWeight,
          color: item.color,
          backgroundColor: item.backgroundColor,
          customizeStyleFlag: item.customizeStyleFlag,
          clickScript: item.clickScript,
          serverSortFlag: item.serverSortFlag
        };
      }) || []
    };
  }, [options.columns]);

  const addTabs = () => {
    setIndex(null);
    changeControlProps(
      'tabsOption',
      [...(options.tabsOption || []), {
        id: uuid(),
        lable: 'lable' + ((options.tabsOption?.length || 0) + 1),
        value: 'value' + uuid(),
        url: options.url || options.tabsOption?.[0]?.['url'] || '',
        query: options.tabsOption?.[0]?.['query'] || '',
        columns: options.columns || options.tabsOption?.[0]?.['columns'] || [],
        actionBtnGroup: [
          { text: '编辑', type: 'edit', scriptText: '', url: '', key: 'edit' },
          { text: '删除', type: 'delete', scriptText: '', url: '', key: 'delete' },
        ]
      }]
    );
  };

  const deleteTabs = (index: number) => {
    setIndex(null);
    changeControlProps(
      'tabsOption',
      options.tabsOption?.filter((_, i) => i !== index)
    );
  };

  const moveTabs = (tabsOption: TabsOptionProps[]) => {
    changeControlProps(
      'tabsOption',
      tabsOption
    );
  };

  const onInputChange = (key: string, value: string | boolean | any[]) => {
    _setCurColumn(prev => ({ ...prev, [key]: value }));
    changeControlProps(
      'tabsOption',
      options.tabsOption?.map((item, i) => {
        return i === index ? { ...item, [key]: value } : item;
      })
    );
  };

  const onActionBtnChange = (actionBtnGroup: any[]) => {
    _setCurColumn(prev => ({ ...prev, actionBtnGroup }));
    changeControlProps(
      'tabsOption',
      options.tabsOption?.map((item, i) => {
        return i === index ? { ...item, actionBtnGroup } : item;
      })
    );
  };

  const onChangeColumns = (value: DataItemProps[]) => {
    let _columns = value.map((item: DataItemProps) => {
      return {
        title: item.label,
        titleEn: item.labelEn,
        dataIndex: item.value,
        formName: item.formName,
        breadCrumbName: item.breadCrumbName,
        dateFormat: item.dateFormat,
        width: item.width,
        fixed: item.fixed,
        moneyFormat: item.moneyFormat,
        statusTransfer: item.statusTransfer,
        statusTransferEn: item.statusTransferEn,
        text: item.text,
        key: item.key,
        customizeStyleFlag: item.customizeStyleFlag,
        fontSize: item.fontSize,
        fontWeight: item.fontWeight,
        color: item.color,
        backgroundColor: item.backgroundColor,
        clickScript: item.clickScript,
        serverSortFlag: item.serverSortFlag
      };
    });
    _setCurColumn(prev => ({ ...prev, columns: _columns }));
    changeControlProps(
      'tabsOption',
      options.tabsOption?.map((item, i) => {
        return i === index ? { ...item, columns: _columns } : item;
      })
    );
  };

  function changeNoTabsColumns(_: unknown, value: DataListProps['columns']) {
    changeControlProps(
      'columns',
      value!.map((item: Record<string, string>) => {
        return {
          title: item.label,
          titleEn: item.labelEn,
          dataIndex: item.value,
          formName: item.formName,
          breadCrumbName: item.breadCrumbName,
          dateFormat: item.dateFormat,
          width: item.width,
          fixed: item.fixed,
          moneyFormat: item.moneyFormat,
          statusTransfer: item.statusTransfer,
          statusTransferEn: item.statusTransferEn,
          text: item.text,
          key: item.key,
          customizeStyleFlag: item.customizeStyleFlag,
          fontSize: item.fontSize,
          fontWeight: item.fontWeight,
          color: item.color,
          backgroundColor: item.backgroundColor,
          clickScript: item.clickScript,
          serverSortFlag: item.serverSortFlag
        };
      })
    );
  }

  return curColumn.id ?
    <ItemController
      curColumn={curColumn}
      onInputChange={onInputChange}
      onActionBtnChange={onActionBtnChange}
      onChangeColumns={onChangeColumns}
    /> : (
      <>
        <FormItem label="数据绑定ID" tooltip="数据存储的名称/英文/必填">
          <Input
            defaultValue={options.name}
            onBlur={e => {
              changeControlProps(
                'name',
                e.target.value
              );
            }} />
        </FormItem>

        <FormItem label="显示搜索" className="antd-form-item-row" tooltip="表头上是否显示搜索组件">
          <Checkbox onChange={(e) => changeControlProps(
            'showSearch',
            e.target.checked
          )} checked={options.showSearch} />
        </FormItem>


        {options.showSearch && <FormItem label="模糊搜索字段" tooltip="模糊搜索列的字段">
          <Select
            mode="multiple"
            value={(options.fuzzyField as any)?.map((item: any) => item.value)}
            onChange={(e: any, opt: any) => {
              changeControlProps(
                'fuzzyField',
                opt
              );
            }}
            fieldNames={{ label: 'label', value: 'value' }}
            url=""
            dataSource={options.showTabs ? getTabsOptionCombineColumns(options.tabsOption || []) : _options.dataSource}
            placeholder="请选择模糊搜索列"
          />
        </FormItem>}

        <ButtonGroup
          tabSource={options.showTabs ? options.tabsOption || [] : undefined}
          dataSource={options.btnGroup || []}
          changeControlProps={(value) => {
            changeControlProps(
              'btnGroup',
              value
            );
          }} />

        <FormItem label='居左显示' className='antd-form-item-row' tooltip="搜索框和按钮组是否居左显示,有选项卡该配置无效">
            <Checkbox 
              checked={options.isActionBtnAlignLeft}
              onChange={e => {
                changeControlProps(
                  'isActionBtnAlignLeft',
                  e.target.checked
                );
              }}/>
          </FormItem>

        <FormItem label="显示选项卡" className="antd-form-item-row">
          <Checkbox onChange={(e) => changeControlProps(
            'showTabs',
            e.target.checked
          )} checked={options.showTabs} />
        </FormItem>

        {options.showTabs && <Columns
          addTabs={addTabs}
          deleteTabs={deleteTabs}
          moveTabs={moveTabs}
          setCurColumn={setCurColumn}
          tabsOption={options.tabsOption || []}
        />}

        {!options.showTabs && <> <FormItem label='数据获取Url'>
          <Input
            defaultValue={options.url}
            onBlur={e => {
              changeControlProps('url', e.target.value);
            }} />
        </FormItem>

          <FormItem label="query">
            <Input
              defaultValue={options.query}
              onBlur={e => changeControlProps('query', e.target.value)} />
          </FormItem>

          <ActionSettingController
            onChange={(value: string | boolean, key: string) => changeControlProps(key, value)}
            formName={options.formName}
            addUrl={options.addUrl}
            hideAddBtn={options.hideAddBtn}
            jumpNewPage={options.jumpNewPage}
            showRowSelection={options.showRowSelection}
            breadCrumbName={options.breadCrumbName}
          />

          <ActionButtonGroup
            dataSource={options.actionBtnGroup || []}
            changeControlProps={(value) => {
              changeControlProps(
                'actionBtnGroup',
                value
              );
            }} />

          <OptionSetting
            name='配置列'
            options={_options}
            editInModal
            formItems={formItems}
            changeControlProps={changeNoTabsColumns}
            formExtra={(initialValues, setInitialValues) => (
              <Form>
                <FormItem label='服务器排序'>
                  <Checkbox
                    checked={initialValues.serverSortFlag}
                    onChange={(e) => setInitialValues({ ...initialValues, serverSortFlag: e.target.checked })} />
                </FormItem>

                <Form.Item label="自定义样式" >
                  <Checkbox
                    onChange={(e) => setInitialValues({ ...initialValues, customizeStyleFlag: e.target.checked })}
                    checked={initialValues.customizeStyleFlag} />
                </Form.Item>
                {initialValues.customizeStyleFlag && (
                  <>
                    <Form.Item label="文字大小" >
                      <Slider
                        step={1}
                        min={12}
                        max={28}
                        value={initialValues.fontSize}
                        onChange={(fontSize: any) => setInitialValues({ ...initialValues, fontSize })} />
                    </Form.Item>

                    <Form.Item label="文字加粗" >
                      <Slider
                        step={100}
                        min={100}
                        max={600}
                        value={initialValues.fontWeight}
                        onChange={(fontWeight: any) => setInitialValues({ ...initialValues, fontWeight })} />
                    </Form.Item>

                    <Dropdown
                      trigger={['click']}
                      placement='top'
                      overlay={
                        <SketchPicker
                          color={initialValues.backgroundColor}
                          onChange={(color: any) => setInitialValues({ ...initialValues, backgroundColor: color.hex.toLocaleUpperCase() })} />
                      }
                    >
                      <Form.Item label='背景颜色'>
                        <Input
                          readOnly
                          value={initialValues.backgroundColor}
                        />
                      </Form.Item>
                    </Dropdown>

                    <Dropdown
                      trigger={['click']}
                      placement='top'
                      overlay={
                        <SketchPicker
                          color={initialValues.color}
                          onChange={(color: any) => setInitialValues({ ...initialValues, color: color.hex.toLocaleUpperCase() })} />
                      }
                    >
                      <Form.Item label='文字颜色'>
                        <Input
                          readOnly
                          value={initialValues.color}
                        />
                      </Form.Item>
                    </Dropdown>
                  </>
                )}
                <CodeMirror
                  label='脚本'
                  scriptText={initialValues.clickScript}
                  change={e => {
                    setInitialValues({
                      ...initialValues,
                      clickScript: e
                    });
                  }} />
              </Form>
            )} />
        </>
        }

        <FormItem label="自动获取数据" className="antd-form-item-row" >
          <Checkbox onChange={(e) => changeControlProps(
            'autoLoad',
            e.target.checked
          )} checked={typeof options.autoLoad === 'boolean' ? options.autoLoad : true} />
        </FormItem>

        <FormItem label="自适应高度" className="antd-form-item-row" >
          <Checkbox onChange={(e) => changeControlProps(
            'autoHeight',
            e.target.checked
          )} checked={typeof options.autoHeight === 'boolean' ? options.autoHeight : true} />
        </FormItem>

        <FormItem label="树结构" className="antd-form-item-row" >
          <Checkbox onChange={(e) => changeControlProps(
            'treeStructure',
            e.target.checked
          )} checked={options.treeStructure} />
        </FormItem>

        {
          options.treeStructure && <>
            <FormItem label="默认展开" className="antd-form-item-row" >
              <Checkbox onChange={(e) => changeControlProps(
                'isExpand',
                e.target.checked
              )} checked={options.isExpand} />
            </FormItem>
            <FormItem label="联动勾选下级" className="antd-form-item-row" >
              <Checkbox onChange={(e) => changeControlProps(
                'checkStrictly',
                e.target.checked
              )} checked={options.checkStrictly} />
            </FormItem>
            <FormItem label="ID" tooltip="父元素的子数据关联属性">
              <Input
                defaultValue={options.treeId}
                onBlur={e => {
                  changeControlProps(
                    'treeId',
                    e.target.value
                  );
                }} />
            </FormItem>
            <FormItem label="ParentID" tooltip="子数据关联父元素的属性">
              <Input
                defaultValue={options.treeParentId}
                onBlur={e => {
                  changeControlProps(
                    'treeParentId',
                    e.target.value
                  );
                }} />
            </FormItem>
          </>
        }

        <CodeMirror
          label='行样式(脚本)'
          scriptText={options.rowCustomizationScript}
          change={e => {
            changeControlProps('rowCustomizationScript', e);
          }} />
      </>
    );
};

export default DataListController;